using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using TCClientService;
using TCEntity;

namespace TimeCameraWinForm
{
  public partial class MainForm : Form
  {
    readonly User user;
    readonly HttpClient client;
    event MethodInvoker OnWait, OnFinished, OnFinishedDownloadSelected;
    List<Image> images = new List<Image>();
    int[] order = new int[5];//用户喜好排行
    List<Image> shares = new List<Image>();
    int picPointer, sharePointer;
    void ErrorBox(string message) =>
      MessageBox.Show(this, message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    void InfoBox(string message) =>
      MessageBox.Show(this, message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    void InternetError() => ErrorBox("网络状态异常，或者服务器未启动。");
    async Task SendAsync(Action success, Func<User, Action, Action<string>, Action, Task> method)
    {
      Invoke(OnWait);
      await method(user, success, ErrorBox, InternetError);
      Invoke(OnFinished);
    }
    async Task SendAsync(Action success, string message, Func<User, string, Action, Action<string>, Action, Task> method)
    {
      Invoke(OnWait);
      await method(user, message, success, ErrorBox, InternetError);
      Invoke(OnFinished);
    }
    async Task DownloadSelected()
    {
      Invoke(OnWait);
      await client.DownloadAsync(user, calendar.SelectionStart, images => this.images = images, ErrorBox, InternetError);
      InitPic();
      Invoke(OnFinishedDownloadSelected);
    }
   
    void WaitCursor() => Cursor = Cursors.WaitCursor;
    void NormalCursor() => Cursor = Cursors.Default;

    void ChangePswdSuccess()
    {
      InfoBox("修改成功！请重新登录。");
      Owner.Show();
      DialogResult = DialogResult.Yes;
      //Login.reload(client);
      Close();
    }
    void DeleteAccountSuccess()
    {
      InfoBox("删除成功！");
      Owner.Show();
      DialogResult = DialogResult.Yes;
      Close();
    }

    private void ChangePswd_Click(object sender, EventArgs e)
    {
      string newpass = newPassword.Text;
      _ = SendAsync(ChangePswdSuccess, newpass, client.ChangePswdAsync);
    }

    private void DeleteAccount_Click(object sender, EventArgs e)
    {
      _ = SendAsync(DeleteAccountSuccess, client.DeleteAccountAsync);
    }

    private void Logout_Click(object sender, EventArgs e)
    {
      DialogResult = DialogResult.Yes;
      Owner.Show();
      Close();
    }
    //-------------------------------------------------
    //我的界面代码部分
    void LoadPic()
    {
      pictureBox1.Image = System.Drawing.Image.FromStream(new MemoryStream(images[picPointer].Picture));
    }
    void InitPic()
    {
      if (images.Count == 0)
      {
        InfoBox("当前日期没有图片。");
        picPointer = -1;
      }
      else
      {
        picPointer = 0;
        LoadPic();
      }
    }

    public MainForm(User user, HttpClient client)
    {
      InitializeComponent();
      this.user = user;
      this.client = client;
      usernameLabel.Text = user.Username;
      favorOrder();
      _=init();
      sharePic.Click += viewPicture;
      OnWait += () => { };
      OnFinished += () => { };
      OnFinishedDownloadSelected += () => { };
      //OnWait += WaitCursor;
      //OnFinished += NormalCursor;
      //OnFinishedDownloadSelected += NormalCursor;
      //OnFinishedDownloadSelected += InitPic;
    }
    private async Task init()
    {
      Image image1 = new Image(1, "http://cs.whu.edu.cn/upload2018/202104/12/202104121443419306.png");
      Image image2 = new Image(2, "http://cs.whu.edu.cn/upload2018/202106/02/202106022106501491.jpg");
      Image image3 = new Image(3, "http://cs.whu.edu.cn/upload2018/202106/02/202106022107370688.jpg");
      Image image4 = new Image(4, "http://cs.whu.edu.cn/upload2018/202106/02/202106022108232154.jpg");
      image1.Picture = Image.Getbyte(image1.ImagePath);
      image2.Picture = Image.Getbyte(image2.ImagePath);
      image3.Picture = Image.Getbyte(image3.ImagePath);
      image4.Picture = Image.Getbyte(image4.ImagePath);
      await client.ShareAsync(image1, () => { }, _ => { }, () => { });
      await client.ShareAsync(image2, () => { }, _ => { }, () => { });
      await client.ShareAsync(image3, () => { }, _ => { }, () => { });
      await client.ShareAsync(image4, () => { }, _ => { }, () => { });
      sharePointer = 0;
      await fetchImageByFavorOrder();
      Invoke(new MethodInvoker(loadSharedPicture));
    }

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
      if (DialogResult == DialogResult.Cancel)
        Application.Exit();
    }

    private void Lastone_Click(object sender, EventArgs e)
    {
      if (picPointer <= 0) InfoBox("已经是第一张图片。");
      else
      {
        picPointer--;
        LoadPic();
      }
    }
 
    private void Nextone_Click(object sender, EventArgs e)
    {
      if (picPointer >= images.Count - 1) InfoBox("已经是最后一张图片。");
      else
      {
        picPointer++;
        LoadPic();
      }
    }

    private void Download_Click(object sender, EventArgs e)
    {
      if (picPointer >= 0 && picPointer < images.Count && DownloadDialog.ShowDialog(this) == DialogResult.OK)
      {
        DownloadDialog.OpenFile().Write(images[picPointer].Picture);
        InfoBox("下载成功。");
      }
    }

    private void Upload_Click(object sender, EventArgs e)
    {
      if (UploadDialog.ShowDialog(this) == DialogResult.OK)
      {
        var stream = UploadDialog.OpenFile();
        byte[] pic = new byte[stream.Length];
        stream.Read(pic);
        _ = client.UploadAsync(user, pic, () => InfoBox("上传成功。"), ErrorBox, InternetError)
          .ContinueWith(_ => DownloadSelected());
        
      }
    }

    private void calendar_DateSelected(object sender, DateRangeEventArgs e)
    {
      _ = DownloadSelected();
    }

    private void ShareButton_Click(object sender, EventArgs e)
    {
      new ShareDetailForm(images[picPointer],client).ShowDialog();
      _=fetchImageByFavorOrder();
      InitShare();
    }

    private void DeleteButton_Click(object sender, EventArgs e)
    {
      _ = DeleteLocal();
    }
    async Task DeleteLocal()
    {
      if (picPointer >= 0 && picPointer < images.Count)
      {
        await client.DeleteAsync(user, images[picPointer].Id, () => InfoBox("成功删除。"), ErrorBox, InternetError);
        await DownloadSelected();
      }
    }

    private void shoot_Click(object sender, EventArgs e)
    {
      new ShootForm().ShowDialog();
    }

    private void tabPage_Mine_Enter(object sender, EventArgs e)
    {
      _ = DownloadSelected();
    }
    //---------------------------------------------------
    //发现界面代码部分
    //对用户喜好进行排序
    public void favorOrder()
    {
      int temp1 = 0, temp2 = 0;
      for (int i = 0; i < order.Length; i++)
        order[i] = user.imageFavor[i];
      for (int i = 0; i < order.Length; i++)
      {
        for (int j = i; j < order.Length; j++)
        {
          if (temp1 < order[j])
          {
            temp1 = order[j];
            temp2 = j;
          }
        }
        if (temp1 > order[i])
        {
          order[temp2] = order[i];
          order[i] = temp2;
        }
        else order[i] = i;
      }
    }

    public async Task fetchImageByFavorOrder()
    {
      await client.FilterAsync( order, filter => shares = filter, _ => { }, () => { });
    }

    void InitShare()
    {
      if (shares.Count == 0)
      {
        InfoBox("当前日期没有图片。");
        sharePointer = -1;
      }
      else
      {
        sharePointer = 0;
        loadSharedPicture();
      }
    }
    private void loadSharedPicture()
    {
      if(sharePointer>=0&&sharePointer<shares.Count)
      sharePic.Image = System.Drawing.Image.FromStream(new MemoryStream(shares[sharePointer].Picture));
      sharePic.SizeMode = PictureBoxSizeMode.StretchImage;
    }

    private void btn_Refresh_Click(object sender, EventArgs e)
    {
      _=fetchImageByFavorOrder();
      InitShare();
    }

    private void LastShare_Click(object sender, EventArgs e)
    {
      if (sharePointer <= 0)
      {
        InfoBox("已是第一张。");
      }
      else
      {
        sharePointer--;
        loadSharedPicture();
      }
    }

    private void NextShare_Click(object sender, EventArgs e)
    {
      if (sharePointer >= shares.Count - 1)
      {
        InfoBox("已是最后一张。");
      }
      else
      {
        sharePointer++;
        loadSharedPicture();
      }
    }

    public void viewPicture(object o, EventArgs e)
    {
      for (int j = 0; j < shares[sharePointer].ImageCategory.Length; j++)
      {
        if (shares[sharePointer].ImageCategory[j] == 1) user.imageFavor[j]++;
      }
      new PictureForm(shares[sharePointer]).ShowDialog();
    }

  }
}
